package com.itmayiedu.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {

	private static final String UPLOAD_IMAGE = "/static/upload/image";

	/**
	 * 跳转到富文本编辑页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String upload() {
		return "upload";
	}

	/**
	 * 上传图片
	 */
	@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> uploadImage(@RequestParam(value = "files", required = false) List<MultipartFile> files,
			HttpServletRequest request) {
		System.out.println(">>>>>" + files);
		Map<String, Object> result = new HashMap<>();
		String imgUrls[] = new String[files.size()];

		// 文件存放的路径
		String filePath = request.getSession().getServletContext().getRealPath(UPLOAD_IMAGE);
		System.out.println(filePath);

		if (files != null && files.size() > 0) {

			for (int i = 0; i < files.size(); i++) {
				MultipartFile multipartFile = files.get(i);
				// System.out.println(String.format("文件名称:%s",
				// multipartFile.getOriginalFilename()));
				String fileName = multipartFile.getOriginalFilename();
				String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
				// System.out.println(String.format("后缀名:%s", fileSuffix));
				fileName = UUID.randomUUID().toString().replace("-", "") + fileSuffix;
				// System.out.println(fileName);

				// 判断路径是否存在，不存在则创建文件夹
				File file = new File(filePath);
				if (!file.exists()) {
					file.mkdir();
				}

				// 将文件写入目标
				file = new File(filePath, fileName);
				try {
					multipartFile.transferTo(file);
				} catch (IOException e) {
					e.printStackTrace();
				}

				// 获取服务端路径
				String serverPath = String.format("%s://%s:%s%s%s", request.getScheme(), request.getServerName(),
						request.getServerPort(), request.getContextPath(), UPLOAD_IMAGE);
				;
				 
				imgUrls[i]=serverPath+"/"+fileName;
				System.out.println(imgUrls[i]);
			}

		}

		result.put("errno", 0);
		result.put("data", imgUrls);
		return result;
	}

}
